import Vue from 'vue';
import store from '../store';
import router from '@/router';
import { app } from '@isyscore/messenger';
import Axios, { apiVersion, userToken, processFault, errorTrace } from '@isyscore/axios';
import { error, warning } from '@/utils/message';

const axios = Axios.create();

const apiVersion1Feature = apiVersion({
    version: '1.0'
});
const userTokenFeature = userToken({
    headerKey: 'token',
    // tokenVal: () => (store.state.sso ? store.state.sso.token : '')
    tokenVal() {
        return app.getUserToken() || store.state.sso ? store.state.sso.token : '';
    }
});

const processFaultFeature = processFault({
    appMessenger: app,
    processor(fault) {
        const { message, status, code } = fault;
        if (message) {
            if (code === 1010401) {
                warning(message);
            } else {
                error(message);
            }
        } else {
            error('网络异常，请稍后重试～～');
        }
        if (status === 401) {
            location.href = `${ENVS.ssoUrl}?return=${encodeURIComponent(location.href)}`;
        }
    }
});

axios.interceptors.response.use(
    function (response) {
        if (response?.data?.code === 1040403) {
            store.commit('setCanVisit', false);
        }

        return {
            data: response
        };
        // return response;
    },
    function (error) {
        // Any status codes that falls outside the range of 2xx cause this function to trigger
        // Do something with response error
        return Promise.reject(error);
    }
);

window.$store = store;
// axios.features.use(apiVersion1Feature).use(userTokenFeature).use(standardFeature).use(processFaultFeature);
axios.features
    .use(apiVersion1Feature)
    .use(userTokenFeature)
    .use(processFaultFeature)
    .use(errorTrace({ appMessenger: app }));

Vue.prototype.$http = axios;

export default axios;
